//
//  CLEmbededWebView.swift
//  clreader
//
//  Created by colin on 2019/4/3.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import WebKit

class CLEmbededWebView: UIView {
    
    var webViewHeightChanged:((_ height:CGFloat)->Void)?
    
    var content:String? {
        didSet {
            if oldValue != self.content {
                if let content_ = self.content,
                    let path = Bundle.main.path(forResource: "CLEmbededWebView", ofType: "html"),
                    let template = try? String(contentsOfFile: path) {
                    let html = template.replacingOccurrences(of: "$$$$", with: content_)
                    self.webView?.loadHTMLString(html, baseURL: nil)
                }
            }
        }
    }
    
    private let heightScriptKey = "WebHeight"
    private var webView:WKWebView?
    
    private var contentHeight:CGFloat = 0 {
        didSet {
            if oldValue != self.contentHeight {
                self.webViewHeightChanged?(self.contentHeight)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let configuretion = WKWebViewConfiguration()
        // Webview的偏好设置
        configuretion.preferences = WKPreferences()
        configuretion.preferences.minimumFontSize = 10
        configuretion.preferences.javaScriptEnabled = true
        // 默认是不能通过JS自动打开窗口的，必须通过用户交互才能打开
        configuretion.preferences.javaScriptCanOpenWindowsAutomatically = false
        
        // 通过js与webview内容交互配置
        configuretion.userContentController = WKUserContentController()
        
//        let script = WKUserScript(source: "setContent('');", injectionTime: .atDocumentEnd,
//            forMainFrameOnly: true)
//        configuretion.userContentController.addUserScript(script)
        
        //        // 添加一个JS到HTML中，这样就可以直接在JS中调用我们添加的JS方法
        //        let script = WKUserScript(source: "window.webkit.messageHandlers.WebHeight.postMessage({body: '呵呵'});",
        //                                  injectionTime: .AtDocumentEnd,// 在载入时就添加JS
        //            forMainFrameOnly: true) // 只添加到mainFrame中
        //        configuretion.userContentController.addUserScript(script)
        
        // 添加一个名称，就可以在JS通过这个名称发送消息：
        // window.webkit.messageHandlers.AppModel.postMessage({body: 'xxx'})
        configuretion.userContentController.add(self, name: self.heightScriptKey)
        
        self.webView = WKWebView(frame: CGRect.zero, configuration: configuretion)
        self.webView?.navigationDelegate = self
        self.addSubview(self.webView!)
        self.webView?.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.webView?.scrollView.isScrollEnabled = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}

extension CLEmbededWebView : WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("images_onload()") { (response, error) in
            if let error_ = error {
                print(error_)
            } else {
                print(response ?? "")
            }
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .linkActivated {
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }
}

extension CLEmbededWebView : WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        // 如果在开始时就注入有很多的名称，那么我们就需要区分来处理
        if message.name == self.heightScriptKey {
            if let height = (message.body as? JSONObject)?["height"] as? Int {
                self.contentHeight = CGFloat(height + 10)
            }
        }
    }
}
